package com.qsl.task.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("job")
public class JobController {
    private static final Logger LOGGER = LoggerFactory.getLogger(JobController.class);

    @Value("${task.executor.url:http://TASK-EXECUTOR/task/exec?taskId={taskId}}")
    private String taskExecUrl;
    @Resource
    private RestTemplate restTemplate;

    @GetMapping("dispatch")
    public String dispatch(Long jobId) {
        LOGGER.info("收到作业[jobId={}]执行请求", jobId);
        LOGGER.info("作业[jobId={}]拆分任务中...", jobId);
        List<Long> taskIds = Arrays.asList(123L, 666L, 888L, 999L);
        LOGGER.info("作业[jobId={}]拆分完成，得到作业列表[{}]", jobId, taskIds);
        for (Long taskId : taskIds) {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("taskId", taskId);
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                    taskExecUrl, String.class, paramMap);
            LOGGER.info("任务[{}]执行结果：{}", taskId, responseEntity.getBody());
        }
        return "success";
    }
}
